package com.ljj.admin.aspects;

import com.ljj.admin.annotations.Log;
import com.ljj.admin.common.utils.ShiroUtils;
import com.ljj.admin.mybatis.system.beans.SysOperLog;
import com.ljj.admin.mybatis.system.beans.SysUser;
import com.ljj.admin.mybatis.system.services.impl.SysOperLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Method;

@Aspect
@Component
public class LogAspect {

    @Autowired
    private SysOperLogService sysOperLogService;

    //定义切入点
    @Pointcut("@annotation(com.ljj.admin.annotations.Log)")
    public void pointcut(){}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point)
    {
        Object result = null;
        long beginTime = System.currentTimeMillis();
        try {
            // 执行方法
            result = point.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        // 保存日志
        saveLog(point, time);
        return result;
    }


    private void saveLog(ProceedingJoinPoint joinPoint, long time)
    {
        MethodSignature signature=(MethodSignature)joinPoint.getSignature();
        Method method=signature.getMethod();
        SysOperLog sysOperLog=new SysOperLog();
        Log logAnnotation=method.getAnnotation(Log.class);
        if(logAnnotation !=null)
        {
            sysOperLog.setOperLocation(logAnnotation.value());
            sysOperLog.setBusinessType(logAnnotation.businessType().ordinal());
        }
        //获取请求的类名称
        sysOperLog.setExecDuration(time);
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysOperLog.setMethod(className + "." + methodName + "()");

        //请求
        SysUser sysUser = ShiroUtils.getSysUser();
        if(!ObjectUtils.isEmpty(sysUser))
        {
            sysOperLog.setOperIp(ShiroUtils.getSession().getHost());
            sysOperLog.setOperId(sysUser.getUserId());
            sysOperLog.setOperName(sysUser.getUserName());

        }


    }

}
